# 用户管理


from django.shortcuts import render,HttpResponse,redirect

from web.models import user

from django import forms

def index(request):

    # 获取全部用户信息
    user_info_all = user.objects.all()
    content = {
        "user_info_all":user_info_all
    }
    return render(request,'后台/user/index.html',content)







class EDITMODELFORMS(forms.ModelForm):
    # account = forms.CharField(error_messages={
    #     'unique':"当前账号已存在"
    # })
    class Meta:
        model = user  #对应的Model中的类
        fields = ['name','account','password','mobile','money']     #字段，如果是__all__,就是表示列出所有的字段
       
    def __init__(self, *args, **kwargs):
          super().__init__(*args, **kwargs)
          # 循环ModelForm中的所有字段，给每个字段的插件设置
          for name, field in self.fields.items():
              # 字段中有属性，保留原来的属性，没有属性，才增加。
              field.widget.attrs = {"class":"form-control","placeholder":field.label}
     

# 编辑用户
def edit_user(request,nid):
    row_objects = user.objects.filter(id=nid).first()
    if request.method == 'GET':
        
        form = EDITMODELFORMS(instance=row_objects)
        return render(request,'后台/user/add_edit.html',{
            "form":form
        })
    
    # POST
    update_object = request.POST

    form = EDITMODELFORMS(data=update_object,instance=row_objects)

    if form.is_valid():
        # 验证成功
        form.save()
        # 重定向返回
        return redirect('/user/index/')
    
    # 验证失败，可能有错误信息
    return render(request,'后台/user/add_edit.html',{
            "form":form
        }) 


# 删除用户
def delete_user(request,nid):
    user.objects.filter(id=nid).delete()
    return redirect('/user/index/')


# 新增用户
def add_user(request):
    # 新增用户
    if request.method == 'GET':
        
        form = EDITMODELFORMS()
        return render(request,'后台/user/add_edit.html',{
            "form":form
        })
    
    # POST
    update_object = request.POST

    form = EDITMODELFORMS(data=update_object)

    if form.is_valid():
        # 验证成功
        form.save()
        # 重定向返回
        return redirect('/user/index/')
    print("验证失败",form)   
    # 验证失败，可能有错误信息
    return render(request,'后台/user/add_edit.html',{
            "form":form
        }) 